package ar.edu.utn.frsf.tpae.a2012.g05.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ar.edu.utn.frsf.tpae.a2012.g05.dao.ClienteDao;
import ar.edu.utn.frsf.tpae.a2012.g05.entity.Cliente;

@Repository
public class ClienteDaoImpl implements ClienteDao{

	@Autowired
	private SessionFactory sessionFactory;
	
	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public Cliente saveOrUpdate(Cliente cliente) {
		getCurrentSession().saveOrUpdate(cliente);
	    return cliente;
	}

	public void delete(Cliente cliente) {
		getCurrentSession().delete(cliente);
	}

	public Cliente findById(Integer id) {
		Cliente cliente;
	    cliente = (Cliente) getCurrentSession().get(Cliente.class, id);
	    return cliente;
	}

	public Cliente findByNumber(String number) {
	    Query query = getCurrentSession().createQuery("from " + Cliente.class.getName()
	            + " where cli_nro = :numero");
	    query.setString("numero", number);
	    Cliente cliente =  (Cliente) query.uniqueResult();
	    return cliente;	}

	@SuppressWarnings("unchecked")
	public List<Cliente> findAll() {
		List<Cliente> clientes = null;
        Query query = getCurrentSession().createQuery("from Cliente");
        clientes = query.list();
		return clientes;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
